package modele.map;


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.imageio.ImageIO;

public class MapParser {
	
	private Color CouleurDominanteDeLaCase[][];
	private TypeTerrain terrain[][];
	private int nbCaseX,nbCaseY,cptX,cptY,caseX,caseY,x,y;
	private String pathCarte;
	private File file;
	private BufferedImage buffer;

	public  MapParser(int nbCaseX,int nbCaseY,String pathCarte) throws IOException{
		this.nbCaseX = nbCaseX;
		this.nbCaseY = nbCaseY;
		this.pathCarte = pathCarte;
		file = new File(this.pathCarte);
		this.buffer = ImageIO.read(file);
		this.x =  this.buffer.getWidth();
		this.y = this.buffer.getHeight();
		this.cptX = 0; 
		this.cptY = 0;
		this.caseX =  x/this.nbCaseX; 
		this.caseY = y/this.nbCaseY;
	}

	public ArrayList<Color> ListeDesCouleurs() throws IOException{
		
		ArrayList<Color> listeDesCouleurs = new ArrayList<>();
		int cptSubImage=0;// LOG

		for(int i=0; i<=this.x-this.caseX;i+=this.caseX){
			for(int j=0; j<=this.y-this.caseY;j+=this.caseY){// parcour les cases

				BufferedImage cell = this.buffer.getSubimage(i, j, this.caseX,this.caseY);
				int cellX =  cell.getWidth();
				int cellY = cell.getHeight();
				System.out.println("----------------SUB IMAGE "+cptSubImage+++"--------------");
				//remplissage du tableau de pixel
				HashMap<Integer,Integer> pixels = new HashMap<>();
				for(int k = 0;k<cellX;k++){
					for(int l = 0;l<cellY;l++){

						int pixel = cell.getRGB(k, l);
						if(pixels.containsKey(pixel)){
							pixels.put(pixel, pixels.get(pixel) + 1);
						}else{
							pixels.put(pixel,1);
						}
					}
				}
				// �valuation du pixel dominant ATTENTION ne marche pas si 2 pixel sont dominant
				int couleurDominante = 0;
				for (Integer p : pixels.keySet()) {
					if(pixels.get(p) > couleurDominante){
						couleurDominante = p;
					}

				}
				Color cd = new Color(couleurDominante);
				if(!listeDesCouleurs.contains(cd)){
					listeDesCouleurs.add(cd);
				}
				this.CouleurDominanteDeLaCase[cptX][cptY]= cd;
			}
		}
		return listeDesCouleurs;
	}

	public TypeTerrain[][] grilleDesTerrain(HashMap<Color, TypeTerrain> listeCouleurTerrain){
		for(int i=0; i<=this.nbCaseX;i++){
			for(int j=0; j<=this.nbCaseY;j++){
				this.terrain[i][j] = listeCouleurTerrain.get(CouleurDominanteDeLaCase[i][j]);
			}
		}
		return this.terrain;	
	}
	public File getFile() {
		return this.file;
	}
}